package com.wkq.controller;

import com.wkq.dao.IPermissionDao;
import com.wkq.domain.Permission;
import com.wkq.domain.Role;
import com.wkq.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private IPermissionDao iPermissionDao;

    @RequestMapping(value = "/addPermissionToRole")
    public String addPermissionToRole(String roleId, String[] ids) {
        if (ids.length > 0 && ids != null) {
            List<String> permissionList = Arrays.asList(ids);
            int flag = iRoleService.addPermissionToRole(roleId, permissionList);
            if (flag > 0) {
                return "redirect:findAll";
            } else {
                return "redirect:addPermissionToRole";
            }
        } else {
            return "redirect:findAll";
        }

    }


    @RequestMapping(value = "/findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(String id) {
        ModelAndView mv = new ModelAndView();
//        1、根据角色Id查询角色
        Role role = iRoleService.findById(Integer.parseInt(id));
//        2、根据角色Id查询出角色没有拥有的资源权限
        List<Permission> permissionList = iPermissionDao.findOtherPermission(id);
//        3、根据角色Id查询出角色拥有的资源权限
        mv.addObject("role", role);
        mv.addObject("permissionList", permissionList);
        mv.setViewName("role-permission-add");
        return mv;
    }

    @RequestMapping(value = "/findById")
    @ResponseBody
    public ModelAndView findById(String id) {
        ModelAndView mv = new ModelAndView();
        Role role = iRoleService.findById(Integer.parseInt(id));
        mv.addObject("role", role);
        mv.setViewName("role-show");
        return mv;
    }

    @RequestMapping(value = "/save")
    public String save(Role role) {
        int flag = iRoleService.save(role);
        if (flag > 0) {
            return "redirect:findAll";
        } else {
            return "redirect:save";
        }
    }

    @RequestMapping(value = "/findAll")
    @ResponseBody
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView();
        List<Role> roleList = iRoleService.findAll();
        mv.addObject("roleList", roleList);
        mv.setViewName("role-list");
        return mv;
    }
}
